package com.hq.myapplicationdemo;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.gson.Gson;
import com.hq.myapplicationdemo.model.Data;
import com.hq.myapplicationdemo.model.HousingInfoBean;
import com.hq.myapplicationdemo.model.HousingSupportingFacilitiesBean;
import com.hq.myapplicationdemo.model.PkShopData;
import com.hq.myapplicationdemo.model.TimeHouseBean;
import com.hq.myapplicationdemo.utils.GlideUtil;
import com.hq.myapplicationdemo.utils.NumericUtils;
import com.hq.myapplicationdemo.utils.XDensityUtils;
import com.hq.myapplicationdemo.views.IDividerItemDecoration;
import com.hq.myapplicationdemo.views.adapter.TabAdapter;
import com.hq.myapplicationdemo.views.view.AnimateScrollView;
import com.hq.myapplicationdemo.views.view.FreeRecyclerView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 店铺pk对比View
 */
public class PkShopActivity extends BaseActivity  {


    FreeRecyclerView rv;
    private List<PkShopData> pkShopData;
    String[] titles = new String[]{
            "|基本信息", "月租金", "建筑面积", "日租金/平米",
            "|租约相关", "支付方式", "押金", "免租期", "起租期", "剩余租约",
            "|经营相关", "经营状态", "当前经营", "交铺时间", "是否临街",
            "|转让相关", "转让费", "是否空转",
            "|物业相关", "物业类型", "所在楼层", "层高", "面宽", "物业费", "配套设施"};
    private TabAdapter mTabAapter;
    private IDividerItemDecoration mIDividerFristmDecoration;
    private ArrayList<String> PosLine;
    private ImageView imageView;//切换横屏竖屏图标

    /**
     * 获取assets下的json文件
     *
     * @param fileName
     * @return
     */
    public  String getJson(String fileName) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName), "utf-8"));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    @Override
    protected void initView() {
        rv = findViewById(R.id.rv);
        initTitleView();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        rv.setLayoutManager(layoutManager);
        initData();


        /**
         * features:
         * 1. 支持divider height 、color 、padding 等熟悉设置
         * 2. 自定义Divider Drawable
         * 3. divider绘制位置。call method {@link #setOffsetMode(int)}
         */
        mIDividerFristmDecoration = new IDividerItemDecoration(this, IDividerItemDecoration.VERTICAL)
               // .setHideFirstLine(true)
                .setVerticalDividerHeight(XDensityUtils.dp2px(getApplicationContext(),0.5f))
                .setOffsetMode(IDividerItemDecoration.OFFSET_MODE_LEFT);
        rv.addItemDecoration(mIDividerFristmDecoration);


    }

    private void initData() {

        //获取上一级页面传过来的商铺id
        //....
        //模拟获取到的数据
        Gson gson = new Gson();
        String jsonStr =getJson("data.json");
        Data shopList   = gson.fromJson(jsonStr, Data.class);



        loadPkShopListView(shopList.getList());
    }

    private String showTxt(String txt) {
        return TextUtils.isEmpty(txt) ? getString(R.string.has_pk_not) : txt;
    }

    /**
     * 初始化标题
     */
    private void initTitleView() {
        View view = findViewById(R.id.layout_title);

        ImageView ivBack = view.findViewById(R.id.iv_back);
        ivBack.setImageResource(R.mipmap.head_back_black);
        ivBack.setOnClickListener(v -> finish());
        TextView tvTitle = view.findViewById(R.id.tv_top_title);
        tvTitle.setText("商铺对比");
         imageView = findViewById(R.id.img_rotatin);

        //旋转
        if (isScreenOriatationPortrait()) {
            imageView.setImageResource(R.mipmap.vs_cross);
        }else{
            imageView.setImageResource(R.mipmap.vs_vertical);
        }
        imageView.setOnClickListener(v -> {
            //旋转
            if (isScreenOriatationPortrait()) {
                imageView.setImageResource(R.mipmap.vs_vertical);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏
            }else{
                imageView.setImageResource(R.mipmap.vs_cross);
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
            }
        });


    }

    /**
     * 返回当前屏幕是否为竖屏。
     *
     * @return 当且仅当当前屏幕为竖屏时返回true, 否则返回false。
     */
    public boolean isScreenOriatationPortrait() {
        return PkShopActivity.this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_pkshop;
    }


    //设置title内容
    private void addTitle(List<HousingInfoBean> shopList, int pkCount) {
        try{
        LinearLayout tab_root = (LinearLayout) findViewById(R.id.tab_root);//填充标题(除第一列 第一行之外)
        LinearLayout ll_content = (LinearLayout) findViewById(R.id.ll_content);//置顶
        LinearLayout ll_title = (LinearLayout) findViewById(R.id.ll_title);//置顶
        ImageView img_switch = (ImageView)findViewById(R.id.img_switch);//差异
        AnimateScrollView scrollView = (AnimateScrollView) findViewById(R.id.scrollView);//顶部滑动
        scrollView.setTag(rv);

        ll_title.setOnClickListener(view13 -> {
            //差异
            if (img_switch.isSelected()) {
                //显示全部
                img_switch.setSelected(false);
                mTabAapter.setDiff(false);
                int itemDecorationCount = rv.getItemDecorationCount();
                if (itemDecorationCount > 0) {
                    rv.removeItemDecorationAt(0);
                }
                rv.addItemDecoration(mIDividerFristmDecoration);
                mTabAapter.notifyDataSetChanged();

            } else {
                //只显示差异
                img_switch.setSelected(true);
                mTabAapter.setDiff(true);

                int itemDecorationCount = rv.getItemDecorationCount();
                if (itemDecorationCount > 0) {
                    rv.removeItemDecorationAt(0);
                }

                IDividerItemDecoration divierDecoration = new IDividerItemDecoration(this, IDividerItemDecoration.VERTICAL)
                        .setPosLine(PosLine)
                        .setVerticalDividerHeight(XDensityUtils.dp2px(PkShopActivity.this,0.5f))
                        .setOffsetMode(IDividerItemDecoration.OFFSET_MODE_LEFT);
                rv.addItemDecoration(divierDecoration);

                mTabAapter.notifyDataSetChanged();
            }
        });
        //LogUtils.i("pk：a2");

        int childCount = ll_content.getChildCount();
      //  LogUtils.i("pk：a3");

            for (int i = 0; i < pkCount; i++) {
              //  LogUtils.i("pk:"+i);
                View v = View.inflate(this, R.layout.pkshop_head, null);

                LinearLayout mLiTabTop = v.findViewById(R.id.ll_tab_top);
                TextView mTvTop = v.findViewById(R.id.tv_ttop);
                ImageView mImgTop = v.findViewById(R.id.img_top);

                TextView mTvTitle = v.findViewById(R.id.tv_title);
                ImageView img_cover = v.findViewById(R.id.img_cover);
                ImageView img_del = v.findViewById(R.id.img_del);//删除


                HousingInfoBean housingInfoBean = shopList.get(i);
                v.setTag(housingInfoBean.getHousingId());//设置tag 为铺源id方便添加时候返回上一级带回
                mTvTitle.setText(housingInfoBean.getTitle());
                GlideUtil.loadImgCenterCropRound(PkShopActivity.this, housingInfoBean.getFrontPicture(), img_cover, 3);
                mLiTabTop.setTag(false);
                mLiTabTop.setOnClickListener(view12 -> {
                    boolean tag = (boolean) mLiTabTop.getTag();
                    //LogUtils.i("刷新----钉" + tag);
                    if (!tag) {
                        //得到view在父容器中的位置下标
                        //判断
                        int index = tab_root.indexOfChild(v);
                        // LogUtils.i("得到view在父容器中的位置下标" + index);
                        //进行置顶
                        mTvTop.setText("已钉住");
                        mTvTop.setTextColor(getResources().getColor(R.color.color_EC6846));
                        mImgTop.setImageResource(R.mipmap.vs_nail_sel);
                        mLiTabTop.setBackgroundResource(R.drawable.shape_contrast_label);
                        mLiTabTop.setTag(true);
                        int nowCount = ll_content.getChildCount();
                        if (childCount != nowCount) {
                            //之前有置顶  先移除回归滑动板
                            View childAt = ll_content.getChildAt(1);
                            LinearLayout mOldLiTabTop = childAt.findViewById(R.id.ll_tab_top);
                            TextView mOldTvTop = childAt.findViewById(R.id.tv_ttop);
                            ImageView mOldImgTop = childAt.findViewById(R.id.img_top);
                            mOldTvTop.setText("钉在左侧");
                            mOldTvTop.setTextColor(getResources().getColor(R.color.color_333333));
                            mOldLiTabTop.setBackgroundResource(R.drawable.shape_contrast_label_nor);
                            mOldImgTop.setImageResource(R.mipmap.vs_nail_nor);
                            mOldLiTabTop.setTag(false);
                            ll_content.removeViewAt(1);
                            tab_root.addView(childAt, 0);
                            tabSuperChanger(1, index + 1);//加上之前置顶的位移1位
                        } else {
                            tabSuperChanger(2, index);
                        }
                        tab_root.removeView(v);
                        ll_content.addView(v, 1);

                    } else {
                        //取消钉住
                        mTvTop.setText("钉在左侧");
                        mTvTop.setTextColor(getResources().getColor(R.color.color_333333));
                        mImgTop.setImageResource(R.mipmap.vs_nail_nor);
                        mLiTabTop.setTag(false);
                        mLiTabTop.setBackgroundResource(R.drawable.shape_contrast_label_nor);
                        ll_content.removeViewAt(1);
                        tab_root.addView(v, 0);
                        tabSuperChanger(3, 0);
                    }
                });
                img_del.setOnClickListener(view14 -> {
                    //删除

                    boolean tag = (boolean) mLiTabTop.getTag();

                    int index = tag ? 0 : tab_root.indexOfChild(v);
                    // LogUtils.i("刷新----钉" + tag + "-index->" + index);

                    boolean tag1 = (boolean) tab_root.getTag();
                    delTableItem(index, !tag1);
                    if (!tag1) {
                        //没有添加就添加一列
                        tab_root.setTag(true);//添加有添加
                        View vAdd = View.inflate(this, R.layout.pkshop_head_add, null);
                        vAdd.setOnClickListener(view1 -> {
                            //添加
                            //去列表页面本结束本页
                            ArrayList<String> strings = new ArrayList<>();
                            int childCount1 = tab_root.getChildCount();
                            for (int j = 0; j < childCount1; j++) {
                                Object ds = tab_root.getChildAt(j).getTag();
                                if (ds != null) {
                                    strings.add((String) ds);
                                }
                            }
                            Intent intent = new Intent();
                            intent.putExtra("houseList", strings);
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                        });
                        tab_root.addView(vAdd);
                    }
                    tab_root.removeView(v);
                    ll_content.removeView(v);

                });
                tab_root.addView(v);
            }


      //  LogUtils.i("pk：a4");
        tab_root.setTag(false);//默认无添加
        if (pkCount < 4) {
            tab_root.setTag(true);//添加有添加
            View vAdd = View.inflate(this, R.layout.pkshop_head_add, null);
            vAdd.setOnClickListener(view1 -> {
                //添加
                //去列表页面本结束本页
                ArrayList<String> strings = new ArrayList<>();
                int childCount1 = tab_root.getChildCount();
                for (int i = 0; i < childCount1; i++) {
                    Object tag = tab_root.getChildAt(i).getTag();
                    if (tag != null) {
                        strings.add((String) tag);
                    }
                }
                Intent intent = new Intent();
                intent.putExtra("houseList", strings);
                setResult(Activity.RESULT_OK, intent);
                finish();
            });
            tab_root.addView(vAdd);
        }
        }catch (Exception e){
           // LogUtils.i("pk：a4"+e.toString());
        }
    }

    /**
     * 删除
     */
    private void delTableItem(int po, boolean isAdd) {
        rv.post(() -> {

            for (int i = 0; i < pkShopData.size(); i++) {
                //移动位置PkShopData pk
                PkShopData pk = pkShopData.get(i);
                List<String> array = pk.getArray();
                array.remove(po);

            }
            if (isAdd) {
                //添加空白tab
                for (int i = 0; i < pkShopData.size(); i++) {
                    //移动位置PkShopData pk
                    PkShopData pk = pkShopData.get(i);
                    List<String> array = pk.getArray();
                    array.add("");
                }
                //少一个补一个 没减少
            } else {
                mTabAapter.setPkCountReduce();
            }
            mTabAapter.notifyDataSetChanged();
        });
    }

    /**
     * @param type 1 开始无钉进行钉住
     *             2 有钉进行钉住切换
     *             3  钉住取消
     * @param po   位置
     */
    private void tabSuperChanger(int type, int po) {

        rv.post(() -> {

            for (int i = 0; i < pkShopData.size(); i++) {
                //移动位置PkShopData pk
                PkShopData pk = pkShopData.get(i);
                List<String> array = pk.getArray();
                //LogUtils.i("刷新----type：" + type + "po:" + po);
               // LogUtils.i("刷新----i1：" + i);
                if (type == 1 || type == 2) {
                    String s = array.get(po);
                    array.remove(po);
                    array.add(0, s);
                    mTabAapter.setTop(true);
                } else if (type == 3) {
                    mTabAapter.setTop(false);
                }
            }
            mTabAapter.notifyDataSetChanged();
        });

    }





    public void loadPkShopListView(List<HousingInfoBean> shopList) {
        int pkCount = shopList.size();
        //数据处理 采用 1比1 等效在 1比1  在 1比1
        //#FDF1EE
        pkShopData = new ArrayList<>();
        PosLine = new ArrayList<>();

        for (int i = 0; i < titles.length; i++) {
            PkShopData data = new PkShopData();
            String title = titles[i];
            data.setName(title);//左边的一列
            List<String> strs = new ArrayList();
            if (title.startsWith("|")) {
                for (int im = 0; im < pkCount;
                     im++) {
                    strs.add("");
                }
            } else {
                if (title.equals("月租金")) {
                    //monthlyRent
                    for (HousingInfoBean bean : shopList) {
                        String shorthand = NumericUtils.shorthand(bean.getMonthlyRent());
                        strs.add(shorthand + "元");
                    }
                } else if (title.equals("建筑面积")) {
                    //constructionArea
                    for (HousingInfoBean bean : shopList) {
                        String shorthand = NumericUtils.shorthand(bean.getConstructionArea());
                        strs.add(shorthand + "㎡");
                    }

                } else if (title.equals("日租金/平米")) {

                    for (HousingInfoBean bean : shopList) {
                        String shorthand = NumericUtils.shorthand((bean.getMonthlyRent() / 30) / bean.getConstructionArea());
                        strs.add(shorthand + "元/㎡");
                    }

                } else if (title.equals("支付方式")) {
                    //paymentMethod
                    for (HousingInfoBean bean : shopList) {
                        strs.add(showTxt(bean.getPaymentMethodDict().getLabel()));
                    }

                } else if (title.equals("押金")) {
                    //paymentMethod
                    for (HousingInfoBean bean : shopList) {
                        String showCash = getString(R.string.has_pk_not);
                        if (bean.getCashPledge() != null) {
                            if (bean.getCashPledge() != -1)
                                showCash = bean.getCashPledge() + "月租金";
                            else {
                                showCash = "面议";
                            }
                        }
                        strs.add(showCash);
                    }

                } else if (title.equals("免租期")) {
                    //paymentMethod
                    for (HousingInfoBean bean : shopList) {
                        String showCash = getString(R.string.has_pk_not);
                        if (bean.getCashPledge() != null) {
                            if (bean.getCashPledge() != -1)
                                showCash = bean.getPaymentMethod() + "天";
                            else {
                                showCash = "面议";
                            }
                        }
                        strs.add(showCash);
                    }
                } else if (title.equals("起租期")) {
                    //shortestLease
                    for (HousingInfoBean bean : shopList) {
                        String showCash = getString(R.string.has_not);
                        //起租期
                        if (bean.getShortestLease() != null) {
                            showCash = bean.getShortestLease() + "个月";
                        }
                        strs.add(showCash);
                    }
                } else if (title.equals("剩余租约")) {
                    //remainingLease
                    for (HousingInfoBean bean : shopList) {
                        String showCash = getString(R.string.has_not);
                        //起租期
                        if (bean.getRemainingLease() != null) {
                            showCash = bean.getRemainingLease() + "个月";
                        }
                        strs.add(showCash);
                    }
                } else if (title.equals("经营状态")) {
                    for (HousingInfoBean bean : shopList) {
                        strs.add(showTxt(bean.getBusinessStatusDict().getLabel()));
                    }
                } else if (title.equals("当前经营")) {
                    for (HousingInfoBean bean : shopList) {
                        strs.add(showTxt(bean.getBusinessIndustry().getShowName()));
                    }
                } else if (title.equals("交铺时间")) {
                    for (HousingInfoBean bean : shopList) {
                        //交铺时间
                        String showCash = getString(R.string.has_not);
                        if (bean.getHandoverTime() != null) {
                            showCash = bean.getHandoverTime().equals("0") ? "随时" : bean.getHandoverTime();
                        }
                        strs.add(showCash);
                    }
                } else if (title.equals("是否临街")) {
                    for (HousingInfoBean bean : shopList) {
                        //是否临街whetherStreet
                        String showCash = "否";
                        if (bean.getWhetherStreet() != null) {
                            showCash = bean.getWhetherStreet() ? "是" : "否";
                        }
                        strs.add(showCash);
                    }
                } else if (title.equals("转让费")) {
                    for (HousingInfoBean bean : shopList) {
                        //是否临街whetherStreet
                        String showCash;
                        int transferState = bean.getTransfer();
                        String showTranMoney = bean.getTransferDict().getLabel();
                        if (transferState == 1) {
                            showCash = (getNumShow(bean.getTransferFee()));
                        } else {
                            showCash = showTxt(showTranMoney);
                        }
                        strs.add(showCash);
                    }
                } else if (title.equals("是否空转")) {
                    for (HousingInfoBean bean : shopList) {
                        //是否临街whetherStreet
                        String showCash = getString(R.string.has_not);
                        if (bean.getWhetherIdling() != null) {
                            showCash = bean.getWhetherIdling() ? getString(R.string.details_transfer_empty) : getString(R.string.details_transfer_no_empty);
                        }
                        strs.add(showCash);
                    }
                } else if (title.equals("物业类型")) {
                    for (HousingInfoBean bean : shopList) {
                        strs.add(showTxt(bean.getPropertyTypeDict().getLabel()));
                    }
                } else if (title.equals("所在楼层")) {
                    //floor
                    for (HousingInfoBean bean : shopList) {
                        strs.add(bean.getFloor());
                    }
                } else if (title.equals("层高")) {
                    //
                    for (HousingInfoBean bean : shopList) {
                        strs.add(bean.getHigh() == null ? getString(R.string.has_not) : String.format(getString(R.string.details_mi), NumericUtils.shorthand(bean.getHigh(), "#.##")));
                    }
                } else if (title.equals("面宽")) {
                    //
                    for (HousingInfoBean bean : shopList) {
                        strs.add(bean.getWidth() == null ? getString(R.string.has_not) : String.format(getString(R.string.details_mi), NumericUtils.shorthand(bean.getWidth(), "#.##")));
                    }
                } else if (title.equals("物业费")) {
                    //
                    for (HousingInfoBean bean : shopList) {
                        strs.add(bean.getPropertyCosts() == null ? getString(R.string.has_not) : String.format(getString(R.string.details_yuan_month_m), NumericUtils.shorthand(bean.getPropertyCosts(), "#.##")));
                    }
                } else if (title.equals("配套设施")) {
                    try {
                        for (HousingInfoBean bean : shopList) {
                            List<HousingSupportingFacilitiesBean> housingSupportingFacilitiesList = bean.getHousingSupportingFacilitiesList();
                            StringBuilder stringBuilder = new StringBuilder();
                            for (int j = 0; j < housingSupportingFacilitiesList.size(); j++) {
                                HousingSupportingFacilitiesBean hbean = housingSupportingFacilitiesList.get(j);
                                stringBuilder.append(hbean.getDict().getLabel());
                                if (j != housingSupportingFacilitiesList.size() - 1) {
                                    stringBuilder.append("、");
                                }
                            }
                            if (stringBuilder.length() == 0) {
                                stringBuilder.append(getString(R.string.has_pk_not));
                            }
                            strs.add(stringBuilder.toString());
                        }
                    } catch (Exception e) {
                       // LogUtils.i("配套设施:" + e.toString());
                    }

                }
            }
            //判断是不是一样数据
            //
            String pkOne = null;
            if (!title.startsWith("|")) {
                for (String ds : strs) {
                    if (pkOne != null) {
                        if (!pkOne.equals(ds)) {
                            data.setDiff(false);
                            //只要存在一次不相等就终止
                            break;
                        }
                    }
                    pkOne = ds;
                }
            }
            if (!data.isDiff() || title.startsWith("|")) {
                PosLine.add(String.valueOf(i));
            }
            if (pkCount < 4) {
                strs.add("");
            }
            data.setArray(strs);

            pkShopData.add(data);
        }

        mTabAapter = new TabAdapter(PkShopActivity.this,pkShopData, pkCount < 4 ? pkCount + 1 : pkCount, rv);

       // LogUtils.i("pk："+pkCount);
        addTitle(shopList, pkCount);
        rv.setmCurrentHeader(findViewById(R.id.ll_content));

        rv.setAdapter(mTabAapter);
    }

    private String getNumShow(double num) {
        String string = NumericUtils.shorthand(num, "####.####") + getString(R.string.home_yuan);
        if (num >= 10000) {
            NumberFormat format = new DecimalFormat("####.####");
            string = format.format(num / 10000) + getString(R.string.home_wan_yuan);
            return string;
        }

        return string;
    }

    //重写旋转时方法，不销毁activity
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //旋转
        if (isScreenOriatationPortrait()) {
            imageView.setImageResource(R.mipmap.vs_cross);
        }else{
            imageView.setImageResource(R.mipmap.vs_vertical);
        }
    }


}
